import jwt from "jsonwebtoken";
import config from "../app/config.ts";
import { Context, Next } from "koa";
import { body, middlewares, routeConfig, z } from "koa-swagger-decorator";
import authMiddleware from "@/middleware/auth.middleware.ts";
import { listHandle } from "@/utils/sql.ts";
import { error } from "console";

// 请求体
const LoginSchema = z.object({
  username: z.string().min(3).max(50),
  password: z.string().min(6),
});

// 请求类型
const postType: Record<string, number> = {
  add: 1,
  delete: 2,
  update: 4,
};

export class AuthController {
  @routeConfig({
    method: "post",
    path: "/login",
    summary: "登录",
    tags: ["Auth"],
  })
  @body(LoginSchema)
  @middlewares([authMiddleware.verifyLogin])
  async login(ctx: Context, next: Next) {
    // 颁发token
    const { id, username } = ctx.user;
    const token = jwt.sign({ id, username }, config.PRIVATE_KEY, {
      expiresIn: 60 * 60 * 24, //一天
      algorithm: "RS256",
    });
    // 设置 HTTP-only Cookie
    ctx.cookies.set("token", token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 24 * 60 * 60 * 1000, // 一天
      sameSite: "strict",
    });

    ctx.body = {
      success: true,
      data: {
        state: 200,
      },
    };
  }
  @routeConfig({
    method: "get",
    path: "/logout",
    summary: "登出",
    tags: ["Auth"],
  })
  async logout(ctx: Context, next: Next) {
    // 清除 Cookie
    ctx.cookies.set("token", "", {
      httpOnly: true,
      expires: new Date(0), // 立即过期
    });

    ctx.body = { success: true, message: "退出登录成功" };
  }

  async success(ctx: Context, next: Next) {
    const { name } = ctx.user;
    ctx.body = `用户:${name}登录授权成功,欢迎您回来`;
  }
  @routeConfig({
    method: "get",
    path: "/auth/list",
    summary: "权限菜单",
    tags: ["Auth"],
    request: {
      query: z.object({
        id: z.string(),
      }),
    },
  })
  @middlewares([authMiddleware.verifyAuth])
  async list(ctx: Context, next: Next) {
    try {
      const ans = await listHandle({ id: ctx.request.query.id }, "auth");
      ctx.body = {
        success: true,
        data: ans,
        errorMessage: null,
      };
      ctx.status = 200;
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "获取权限菜单失败",
      };
      ctx.status = error.status || 400;
    }
  }
  @routeConfig({
    method: "get",
    path: "/auth/verify",
    summary: "验证权限",
    tags: ["Auth"],
    request: {
      query: z.object({
        path: z.string(),
        type: z.string(),
      }),
    },
  })
  @middlewares([authMiddleware.verifyAuth])
  async verify(ctx: Context, next: Next) {
    try {
      const ans = await listHandle({ id: ctx.state.user.id }, "auth");
      console.log(ans);
      // 应对多级菜单
      const path = ctx.query.path as string;
      // 匹配的路径
      const partner: any[] = [];
      let can = false;
      ans.list.forEach((item) => {
        if (path === item.path) {
          if (ctx.query.type !== "list") {
            console.log(ctx.query.type);
            let type = postType[ctx.query.type as string];
            console.log(type, item.oper, type & item.oper);
            if (type & item.oper) {
              can = true;
            }
          } else {
            can = true;
          }
        }
      });

      console.log(can);
      ctx.status = 200;
      if (can) {
        ctx.body = {
          success: true,
          data: true,
          errorMessage: null,
        };
      } else {
        ctx.body = {
          success: true,
          data: false,
          errorMessage: null,
        };
      }
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "权限获取失败",
      };
      ctx.status = error.status || 400;
    }
  }
}
